package com.efounder.zone.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.zone.R;
import com.efounder.zone.bean.TalksBean;
import com.efounder.zone.event.MobileZoneFilterEvent;
import com.efounder.zone.util.ZoneRequestUtil;
import com.utilcode.util.ScreenUtils;

import net.sf.json.JSONObject;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 空间动态编辑popupWindow
 * Created by slp on 2018/5/14.
 */
public class ZoneRedactPopupWindow extends PopupWindow {

    private static String TAG = "ZoneRedactPopupWindow";

    private Context mContext;

    private View mConentView;
    private LinearLayout llDynamicGeneration;
    private ImageView ivArrowUp;
    private ImageView ivArrowDown;
    private OnDeleteClickListener mDeleteClickListener;

    private TalksBean mTalksBean;
    private WeChatDBManager mWeChatDBManager;
    int[] location = new int[2];
    private List<RedactMenuBean> mRedactMenuList;

    //是否已经关注
    private boolean isFoucs = false;

    public ZoneRedactPopupWindow(Context context, TalksBean talksBean, OnDeleteClickListener listener) {
        super(context);
        this.mContext = context;
        this.mTalksBean = talksBean;
        this.mDeleteClickListener = listener;
        mWeChatDBManager = WeChatDBManager.getInstance();
        mRedactMenuList = new ArrayList<>();
        // setMenu();

    }

    public void setIsFocus(boolean isFocus) {
        this.isFoucs = isFocus;
        setMenu();
        initView();
    }

    /**
     * 设置要显示的菜单数据
     */
    private void setMenu() {
        int userid = Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        if (userid == mTalksBean.getObj().getPostAuthor()) {
            mRedactMenuList.add(new RedactMenuBean(R.drawable.mobile_zone_item_delete, ResStringUtil.getString(R.string.common_text_delete)));
        } else {
            User user = mWeChatDBManager.getOneFriendById( mTalksBean.getObj().getPostAuthor());
            if (!user.isExist()) {
                mRedactMenuList.add(new RedactMenuBean(R.drawable.mobile_zone_item_add, ResStringUtil.getString(R.string.zone_add_friend)));
            }
            if (isFoucs) {
                mRedactMenuList.add(new RedactMenuBean(R.drawable.mobile_zone_item_follow, ResStringUtil.getString(R.string.zone_cancel_follow)));
            } else {
                mRedactMenuList.add(new RedactMenuBean(R.drawable.mobile_zone_item_follow, ResStringUtil.getString(R.string.zone_add_follow)));
            }

            mRedactMenuList.add(new RedactMenuBean(R.drawable.mobile_zone_item_hide, ResStringUtil.getString(R.string.zone_add_blacklist)));
        }
    }


    private void initView() {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.mConentView = inflater.inflate(R.layout.mobile_zone_popupwindow_redact, null);
        llDynamicGeneration = mConentView.findViewById(R.id.ll_dynamic_generation);
        ivArrowUp = mConentView.findViewById(R.id.iv_arrow_up);
        ivArrowDown = mConentView.findViewById(R.id.iv_arrow_down);
        //动态生成菜单选项
        for (int i = 0; i < mRedactMenuList.size(); i++) {
            RedactMenuBean redactMenuBean = mRedactMenuList.get(i);
            ViewGroup menuItem = (ViewGroup) inflater.inflate(
                    R.layout.mobile_zone_menu_item, null);

            ImageView ivMenuIcon = (ImageView) menuItem.findViewById(R.id.iv_menu_icon);
            TextView tvMenuText = (TextView) menuItem.findViewById(R.id.tv_menu_text);
            View viewLine = menuItem.findViewById(R.id.view_line);

            ivMenuIcon.setImageResource(redactMenuBean.icon);
            tvMenuText.setText(redactMenuBean.text);

            menuItem.setOnClickListener(new MyOnclickListener(redactMenuBean));
            //最后一个菜单选项不显示分割线
            if ((i + 1) == mRedactMenuList.size()) {
                viewLine.setVisibility(View.GONE);
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            llDynamicGeneration.addView(menuItem, lp);
        }

        // 设置SelectPicPopupWindow的View
        this.setContentView(mConentView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        // 刷新状态
        this.update();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0000000000);
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        this.setBackgroundDrawable(dw);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.AnimationPreview);
    }

    /**
     * 根据参考控件的位置展示popupwindow
     *
     * @param v 位置参考控件
     */
    public void showPopupWindow(View v) {
        WindowManager.LayoutParams params = ((Activity) mContext).getWindow().getAttributes();
        params.alpha = 0.4f;
        ((Activity) mContext).getWindow().setAttributes(params);
        v.getLocationOnScreen(location); //获取控件的位置坐标
        //获取自身的长宽高
        mConentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        //若是控件的y轴位置大于屏幕高度减去弹窗的高度，向上弹出
        if (location[1] > (ScreenUtils.getScreenHeight() - mConentView.getMeasuredHeight())) {
            ivArrowUp.setVisibility(View.GONE);
            ivArrowDown.setVisibility(View.VISIBLE);
            this.showAtLocation(v, Gravity.NO_GRAVITY, (location[0]), location[1] - mConentView.getMeasuredHeight()); //显示指定控件的上方
        } else {
            ivArrowUp.setVisibility(View.VISIBLE);
            ivArrowDown.setVisibility(View.GONE);
            this.showAsDropDown(v, 0, 0);  //显示指定控件的下方
        }
    }


    /**
     * 在屏幕中间展示popupwindow
     */
    private void showPopupWindow() {
        WindowManager.LayoutParams params = ((Activity) mContext).getWindow().getAttributes();
        params.alpha = 0.4f;
        ((Activity) mContext).getWindow().setAttributes(params);

        this.showAtLocation(((Activity) mContext).getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    @Override
    public void dismiss() {
        super.dismiss();
//        取消背景色
        WindowManager.LayoutParams params = ((Activity) mContext).getWindow().getAttributes();
        params.alpha = 1f;

        ((Activity) mContext).getWindow().setAttributes(params);
    }


    /**
     * 删除动态
     */
    private void deleteDynamic() {
        String dynamicId = String.valueOf(mTalksBean.getObj().getId());
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        ZoneRequestUtil.postCommonRequest(TAG, "shortposts/" + dynamicId, params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                mDeleteClickListener.onDeleteSuccess();
            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(mContext, R.string.zone_delete_fail_please_again);
            }
        });
    }

    public interface OnDeleteClickListener {
        /**
         * 动态删除成功
         */
        void onDeleteSuccess();
    }

    /**
     * 菜单bean
     */
    public class RedactMenuBean {
        public int icon;
        public String text;

        public RedactMenuBean(int icon, String text) {
            this.icon = icon;
            this.text = text;
        }
    }

    public class MyOnclickListener implements View.OnClickListener {

        private RedactMenuBean redactMenuBean;

        public MyOnclickListener(RedactMenuBean redactMenuBean) {
            this.redactMenuBean = redactMenuBean;
        }

        @Override
        public void onClick(View v) {
            if (ResStringUtil.getString(R.string.common_text_delete).equals(redactMenuBean.text)) {
                dismiss();
                if (mDeleteClickListener != null) {
                    deleteDynamic();
                }
            } else if (ResStringUtil.getString(R.string.zone_add_follow).equals(redactMenuBean.text)) {
                dismiss();
                if (mDeleteClickListener != null) {
                    foucusRequest(true);
                }
            } else if (ResStringUtil.getString(R.string.zone_cancel_follow).equals(redactMenuBean.text)) {
                dismiss();
                if (mDeleteClickListener != null) {
                    foucusRequest(false);
                }
            } else if (ResStringUtil.getString(R.string.zone_add_friend).equals(redactMenuBean.text)) {
                dismiss();
                Intent intent = new Intent();
                intent.putExtra("id", mTalksBean.getObj().getPostAuthor());
                ChatActivitySkipUtil.startUserInfoActivity(mContext, intent);
            } else if (ResStringUtil.getString(R.string.zone_add_blacklist).equals(redactMenuBean.text)) {
                dismiss();
                addToBlackList();
            }

        }
    }

    //加入黑名单
    private void addToBlackList() {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
        //被关注人id
        params.put("blackUserid", mTalksBean.getObj().getPostAuthor() + "");


        ZoneRequestUtil.getCommonRequest(TAG, "black/add", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = JSONObject.fromObject(response);
                    // {"msg":null,"status":"011999"}
                    if (jsonObject.optString("status", "").equals("111000")) {
                        ToastUtil.showToast(mContext, R.string.zone_add_success);
                        EventBus.getDefault().post(new MobileZoneFilterEvent(mTalksBean.getObj().getPostAuthor(), 1));
                    } else {
                        ToastUtil.showToast(mContext,  R.string.zone_add_fail);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(mContext, R.string.zone_operation_fail_abnormal);
                }
            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(mContext, R.string.zone_operation_fail_abnormal);
            }
        });
    }

    /**
     * 关注或者取消关注
     *
     * @param foucus
     */
    private void foucusRequest(final boolean foucus) {
        HashMap<String, String> params = new HashMap<>();
        params.put("fansId", EnvironmentVariable.getProperty(CHAT_USER_ID));
        //被关注人id
        params.put("starId", mTalksBean.getObj().getPostAuthor() + "");

        String operation = foucus ? "add" : "delete";
        ZoneRequestUtil.getCommonRequest(TAG, "fans/" + operation, params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = JSONObject.fromObject(response);
                    //{"msg":"delete fans success!","status":"105001"}
                    if (jsonObject.optString("status", "").equals("105001")) {
                        //取消关注
                        EventBus.getDefault().post(new MobileZoneFilterEvent(mTalksBean.getObj().getPostAuthor(), 0));
//                        ToastUtil.showToast(mContext, foucus ? "关注成功" : "取消关注成功");
                        ToastUtil.showToast(mContext, R.string.zone_cancel_follow_success);
                    }

                    if (jsonObject.optString("status", "").equals("105000")) {
//                        ToastUtil.showToast(mContext, foucus ? "关注成功" : "取消关注成功");
                        ToastUtil.showToast(mContext, R.string.zone_follow_success);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(mContext, R.string.zone_operation_fail_abnormal);
                }
            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(mContext, R.string.zone_operation_fail_abnormal);
            }
        });
    }
}
